// pages/activity/activity.js
const app = getApp();
import api from '../../../utils/util.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    fullHeight: app.globalData.fullcontain,
    discount: app.globalData.discount,
    navmess:{
      navtitle: "活动",
      backhide: 1,
      topheight: 1
    },
    curIdx: 3,
    currentTab: 0,

    pageNum: [1,1,1,1,1,1],
    pageSize: 2,
    indexType: 1,
    loading: [false,false,false,false,false,false],
    noMore: [false,false,false,false,false,false],
    loadingFailed: [false,false,false,false,false,false],
    //全部
    demolist1: [],
    //秒杀
    demolist2: [],
    //拼团
    demolist3: [],
    // 个人砍价（需登录）
    demolist4: [],
    // 更多砍价（未登录）
    demolist5: [],
    // 优惠券
    couponlist: [],
    // 积分
    demolist6: [],
    //
    setTimeFun: function(that,list,end_time, param,els){
      this.timer = setTimeout(function () {
        if(els == "allseckill"){
          that.countdown(that,list,end_time, param,"allseckill");
        }else{
          that.countdown(that,list,end_time, param);
        }
      }, 1000)
    }
  },
  pageto: function(e){
    var url = e.currentTarget.dataset.url,
        data = e.currentTarget.dataset.datobj;
    app.goto(url,data);
  },
  // 活动-全部
  getAllActivity: function (isfresh) {
    var that = this,
      index = that.data.currentTab,
      pageNum = this.data.pageNum,
      indexType = this.data.indexType,
      demolist1 = this.data.demolist1,
      noMore = this.data.noMore,
      allBargainTemp = this.data.allBargainTemp;
    if (indexType == 6) {
      noMore[0] = true
      that.setData({
        noMore: noMore
      })
      return
    } else {
      // 全部-数据请求
      api.post("/mini/ext/activities", {
        "ent": app.globalData.ent,
        "type": indexType,
        "pageNum": pageNum[0],
        "pageSize": that.data.pageSize
      }).then(res => {
        if (isfresh) {
          that.refreshView.stopPullRefresh()
        }
        var loading = that.data.loading;
        loading[index] = false;
        that.setData({
          loading: loading
        })
        console.log(indexType, res) //对应活动列表
        if (!res.result.activityType) {
          // 当前type接口无数据
          if (indexType == 5) {
            noMore[0] = true
            that.setData({
              noMore: noMore
            })
          } else {
            pageNum[0] = 1;
            indexType = indexType + 1;
            that.setData({
              indexType: indexType,
              pageNum: pageNum
            })
          }
        } else {
          var temp;
          if (indexType == 1) {
            temp = res.result.seckillMiNi.list
            for (var i in temp) {
              temp[i].actType = 1
            }
          } else if (indexType == 2) {
            temp = res.result.spellGroupMiNi.list
            for (var i in temp) {
              temp[i].actType = 2
            }
          } else if (indexType == 3) {
            temp = res.result.bargainMiNi.list
            for (var i in temp) {
              temp[i].actType = 3
            }
          }else if (indexType == 4){
            temp = res.result.couponMiNi.list
            for (var i in temp) {
              temp[i].actType = 4
            }
          }else if (indexType == 5){
            temp = res.result.scoreMiNi.list
            for (var i in temp) {
              temp[i].actType = 5
            }
          }
          console.log("temp", temp)
          if (temp.length == 1) {
            pageNum[0] = 1;
            indexType = indexType + 1;
            that.setData({
              demolist1: demolist1.concat(temp),
              indexType: indexType,
              pageNum: pageNum,
            })
            this.getAllActivity(); //条数不够重复请求
          } else {
            pageNum[0] = pageNum[0] + 1;
            that.setData({
              demolist1: demolist1.concat(temp),
              pageNum: pageNum,
            })
            console.log("demolist1", that.data.demolist1)
          }
          // 遍历的molist1批量设置倒计时
          var data = that.data.demolist1,
          dataName = "demolist1";
          for (var i = 0; i < data.length; i++) {
            if (data[i].actType == 3) {
              var end_time = data[i].endTime;
              that.countdown(that,dataName, end_time, i);
            }else if(data[i].actType == 1){
              var end_time = data[i].endTime;
              that.countdown(that,dataName, end_time, i, "allseckill");
            }
          }
        }
      }).catch(res => {
        console.log(res)
        var loadingFailed = that.data.loadingFailed;
        loadingFailed[index] = true;
        that.setData({
          loadingFailed: loadingFailed
        })
      })
    }
  },
  // 分页数据（除全部）
  getMore: function(type,isfresh){
    var that = this,
        index = that.data.currentTab,
        pageNum = this.data.pageNum,
        noMore = this.data.noMore,
        temp;
    if (noMore[index]) {
      console.log("当前Type没有更多")
      var loading = that.data.loading;
          loading[index] = false;
          noMore[index] = true;
      that.setData({
        loading: loading,
        noMore: noMore
      })
    } else {
      api.post("/mini/ext/activities",{
        "ent": app.globalData.ent,
        "type": type,
        "pageNum": pageNum[type],
        "pageSize": that.data.pageSize
      }).then(res => {
        if (isfresh) {
          that.refreshView.stopPullRefresh()
        }
        var loading = that.data.loading;
            loading[index] = false;
        that.setData({
          loading: loading
        })
        if(res.result.activityType){
          console.log("列表数据: ",res) //列表数据
          pageNum[type]++;
          if (type == 1) {
            temp = res.result.seckillMiNi.list
            that.setData({
              demolist2: that.data.demolist2.concat(temp),
              pageNum: pageNum,
            })
            if(that.data.demolist2.length){
              //批量倒计时
              var data = that.data.demolist2,
              dataName = "demolist2";
              for (var i = 0; i < data.length; i++) {
                var end_time = data[i].endTime;
                that.countdown(that,dataName,end_time, i);
              }
            }
          } else if (type == 2) {
            temp = res.result.spellGroupMiNi.list
            that.setData({
              demolist3: that.data.demolist3.concat(temp),
              pageNum: pageNum
            })
          } else if (type == 3) {
              temp = res.result.bargainMiNi.list
              that.setData({
                demolist5: that.data.demolist5.concat(temp),
                pageNum: pageNum
              })
              if(that.data.demolist5.length){
                //批量倒计时
                var data = that.data.demolist5,
                    dataName = "demolist5";
                for (var i = 0; i < data.length; i++) {
                  var end_time = data[i].endTime;
                  that.countdown(that,dataName,end_time, i);
                }
              }
          } else if (type == 4) {
            temp = res.result.couponMiNi.list
            that.setData({
              couponlist: that.data.couponlist.concat(temp),
              pageNum: pageNum
            })
          } else if (type == 5) {
            temp = res.result.scoreMiNi.list
            that.setData({
              demolist6: that.data.demolist6.concat(temp),
              pageNum: pageNum
            })
          }
        }else{
          noMore[index] = true;
          that.setData({
            noMore: noMore
          })
        }
      }).catch(res => {
        console.log(res)
        var loadingFailed = that.data.loadingFailed;
        loadingFailed[index] = true;
          that.setData({
            loadingFailed: loadingFailed
        })
      })
    }
  },
  // 获取砍价列表
  bargainMess: function (isfresh) {
    var that = this,
      token = this.data.token,
      pageNum = this.data.pageNum,
      index = this.data.currentTab;
    api.post("/mini/my/bargain/bargaining", {
      "token": token,
    }).then(res => {
      if(isfresh){
        that.refreshView.stopPullRefresh()
        that.setData({
          demolist4: []
        })
      }
      console.log("个人砍价", res)
      if(res.code == 200){
        that.setData({
          demolist4: that.data.demolist4.concat(res.result)
        })
        // 查验个人砍价数据有无
        if(that.data.demolist4.length){
          that.setData({
            perBargainlen: 1
          })
          //批量倒计时
          var data = that.data.demolist4,
              dataName = "demolist4";
          for (var i = 0; i < data.length; i++) {
            var end_time = data[i].expiredTime;
            that.countdown(that,dataName,end_time, i);
          }
        }else{
          that.setData({
            perBargainlen: 0
          })
        }
        this.getMore(3);
      }
    })
  },
  // 优惠券列表(分页数量不同)
  getcoupon: function(isfresh){
    var that = this,
        pageNum = this.data.pageNum,
        noMore = this.data.noMore;
    api.post("/mini/ext/activities",{
      "ent": app.globalData.ent,
      "type": 4,
      "pageNum": pageNum[4],
      "pageSize": 3
    }).then(res => {
      if(isfresh){
        that.refreshView.stopPullRefresh()
      }
      var loading = that.data.loading;
          loading[4] = false;
      that.setData({
        loading: loading
      })
      if(res.result.activityType){
        console.log("couponlist",res) 
        pageNum[4]++;
        var temp = res.result.couponMiNi.list
        that.setData({
          couponlist: that.data.couponlist.concat(temp),
          pageNum: pageNum
        })
      }else{
        noMore[4] = true;
        that.setData({
          noMore: noMore
        })
      }
    }).catch(res => {
      console.log(res)
      var loadingFailed = that.data.loadingFailed;
      loadingFailed[4] = true;
        that.setData({
          loadingFailed: loadingFailed
      })
    })
  },
  // 滑动切换tab
  bindChange: function (e) {
    var that = this,
        index = e.detail.current;
    that.setData({
      currentTab: index
    });
    // 列表加载(swiper切换判断加载)
    if(index == 0 && !that.data.demolist1.length){
      that.getAllActivity();
    }else if(index == 1 && !that.data.demolist2.length){
      that.getMore(1);
    }else if(index == 2 && !that.data.demolist3.length){
      that.getMore(2);
    }else if(index == 3 && !that.data.demolist5.length){
      // 是否登录取个人砍价
      if(that.data.isLogin && that.data.hasperbargain){
        that.bargainMess();
      }else{
        that.getMore(3);
      }
    }else if(index == 4 && !that.data.couponlist.length){
      that.getcoupon();
    }else if(index == 5 && !that.data.demolist6.length){
      that.getMore(5);
    }
  },
  // 点击tab切换
  swichNav: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    } 
  },
  // 触底分页请求
  scrollToLower: function(e){
    var that = this,
        index = this.data.currentTab;
    if(index == 0){
      if(that.data.noMore[0]){
        var noMore = that.data.noMore;
        noMore[index] = true;
        that.setData({
          noMore: noMore
        })
      }else{
        //底部提示语
        var loading = that.data.loading;
        loading[index] = true;
        that.setData({
          loading: loading
        })
        that.getAllActivity();
      }
    }else if(index == 3){
      if(that.data.isLogin && that.data.hasperbargain){
        that.bargainMess();
      }else{
        that.getMore(3);
      }
    }else if(index == 4){
      that.getcoupon();
    }else{
      that.getMore(index);
    }
  },
  // top下拉刷新 
  //触摸开始
  handletouchstart: function (event) {
    this.refreshView.handletouchstart(event)
  },
  //触摸移动
  handletouchmove: function (event) {
    this.refreshView.handletouchmove(event)
  },
  //触摸结束
  handletouchend: function (event) {
    this.refreshView.handletouchend(event)
  },
  //触摸取消
  handletouchcancel: function (event) {
    this.refreshView.handletouchcancel(event)
  },
  //页面滚动
  onPageScroll: function (event) {
    this.refreshView.onPageScroll(event)
  },
  onPullDownRefresh:function(){
    console.log("-----下拉刷新-----")
    clearTimeout(this.timer)
    var that = this,
        index = this.data.currentTab;
    this.setData({
      demolist1: [],
      demolist2: [],
      demolist3: [],
      demolist4: [],
      demolist5: [],
      couponlist: [],
      indexType: 1,
      loading: [false,false,false,false,false,false],
      noMore: [false,false,false,false,false,false],
      loadingFailed: [false,false,false,false,false,false],
      pageNum: [1,1,1,1,1,1],
    })
    if(index == 0){
      that.getAllActivity(true);
    }else if(index == 3){
      if(that.data.isLogin && that.data.hasperbargain){
        that.bargainMess(true);
      }else{
        that.getMore(3,true);
      }
    }else if(index == 4){
      that.getcoupon(true);
    }else{
      that.getMore(index,true);
    }
    // setTimeout(() => { this.refreshView.stopPullRefresh()},1500)
  },
  _pullState: function(e){
    // console.log(e.detail) 
  },
  // 点击免费拿
  newbarfun: function(e){
    var that = this;
    if(this.data.isLogin){
      console.log("新建砍价",e.target.dataset.obj);
      that.setData({
        newbargain: true,
        toshareobj: e.target.dataset.obj
      })
    }else{
      wx.navigateTo({
        url: '../../login/login',
      })
    }
  },
  closebarfn: function(e){
    var that = this;
    console.log("砍价窗口返回数据",e.detail); //子组件返回参数
    that.setData({
      newbargain: false,
    })
  },
  // 优惠券领取
  receiveopen: function(e){
    var that = this;
    console.log('优惠券sign：',e.currentTarget.dataset.sign)
    if(that.data.isLogin){
      api.post("/mini/ext/coupon/doReceive",{
        "token": that.data.token,
        "sign": e.currentTarget.dataset.sign
      }).then(res => {
        console.log(res)
        if(res.code == 200){
          that.setData({
            receivestate: true
          })
        }else{
          wx.showToast({
            title: '领取失败',
            icon: "none",
            duration: 1500
          })
        }
      })
    }else{
      wx.navigateTo({
        url: '../../login/login',
      })
    }
  },
  closereceive: function(){
    this.setData({
      receivestate: false
    })
  },
  // 代参详情页跳转
  takegoodto: function(e){
    if(this.data.isLogin){
      wx.navigateTo({
        url: e.currentTarget.dataset.url + "?mess=" + JSON.stringify(e.currentTarget.dataset.mess),
      })
    }else{
      wx.navigateTo({
        url: '../../login/login',
      })
    }
  },
  //封装的倒计时方法
  //批量倒计时
  countdown: function (tha,list,end_time,param,els) {
    var that = tha;
    // console.log(list) // 表示需要批量倒计时的数据列表
    var EndTime = new Date(end_time).getTime();
    var NowTime = new Date().getTime();
    var total_micro_second = EndTime - NowTime;
    
    var lidata = that.data[list];
    if(lidata.length !== 0){
      lidata[param].lastTime = that.dateformats(total_micro_second);
    }
    if (total_micro_second <= 0) {
      lidata[param].lastTime = {
        day: 0,
        hrStr: 0,
        minStr: 0,
        secStr: 0
      }
    }
    if(list == "demolist5"){
      that.setData({
        demolist5: lidata
      })
    }else if(list == "demolist2"){
      lidata[param].lastTime.day = Number(lidata[param].lastTime.day);
      lidata[param].lastTime.hrStr = Number(lidata[param].lastTime.hrStr);
      lidata[param].lastTime.minStr = Number(lidata[param].lastTime.minStr);
      lidata[param].lastTime.secStr = Number(lidata[param].lastTime.secStr);
      that.setData({
        demolist2: lidata
      })
      // console.log(that.data.demolist2[param].lastTime)
    }else if(list == "demolist1"){
      if(els == "allseckill"){
        lidata[param].lastTime.day = Number(lidata[param].lastTime.day);
        lidata[param].lastTime.hrStr = Number(lidata[param].lastTime.hrStr);
        lidata[param].lastTime.minStr = Number(lidata[param].lastTime.minStr);
        lidata[param].lastTime.secStr = Number(lidata[param].lastTime.secStr);
        that.setData({
          demolist1: lidata
        })
      }else{
        that.setData({
          demolist1: lidata
        })
      }
    }else if(list == "demolist4"){
      lidata[param].lastTime.day = Number(lidata[param].lastTime.day);
      lidata[param].lastTime.hrStr = Number(lidata[param].lastTime.hrStr);
      lidata[param].lastTime.minStr = Number(lidata[param].lastTime.minStr);
      lidata[param].lastTime.secStr = Number(lidata[param].lastTime.secStr);
      that.setData({
        demolist4: lidata
      })
    }
    that.data.setTimeFun(that,list,end_time, param,els);
  },
  // 时间格式化输出，每1s都会调用一次
  dateformats: function (micro_second) {
    // 总秒数
    var second = Math.floor(micro_second / 1000);
    // 天数
    var day = Math.floor(second / 3600 / 24);
    // 小时
    var hr = Math.floor(second / 3600 % 24);
    var hrStr = hr.toString();
    if (hrStr.length == 1) hrStr = '0' + hrStr;
    
    // 分钟
    var min = Math.floor(second / 60 % 60);
    var minStr = min.toString();
    if (minStr.length == 1) minStr = '0' + minStr;
    
    // 秒
    var sec = Math.floor(second % 60);
    var secStr = sec.toString();
    if (secStr.length == 1) secStr = '0' + secStr;
    
    var backObj = {
      day: day,
      hrStr: hrStr,
      minStr: minStr,
      secStr: secStr
    }
    if (day <= 1) {
      return backObj;
    } else {
      // console.log(backObj)
      return backObj;
    }
  },
  // 去砍价信息页
  startBargain: function (e) {
    var url = e.currentTarget.dataset.url,
    bargainOrderId = e.currentTarget.dataset.bargainorderid;
    wx.navigateTo({
      url: url +"?bargainOrderId="+ bargainOrderId,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 刷新组件
    this.refreshView = this.selectComponent("#refreshView")
    // 活动-全部
    that.getAllActivity();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //登录标记
    var check = app.checkLogin();
    if(check){
      var token = wx.getStorageSync('token');
      this.setData({
        isLogin: check,
        token: token,
        hasperbargain: true
      })
      this.bargainMess(true);
    }else{
      this.setData({
        hasperbargain: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(setTime);
  }
})